import koa from 'koa'
import SocketRouter from './router/socket' // 导入串口通信中间件
import koaBody from 'koa-body' // 处理post请求和文件上传
import cors from 'koa-cors'
import DeviceStatsRouter from './router/deviceStats'
let app = new koa
import {Server} from 'http'
// 配置跨域
app.use(cors())

// 配置日志信息
import { accessLogger,httpLogger,formatText, logger } from './until/log'
app.use(accessLogger())
app.use(koaBody())

// 监听应用程序接口
app.use(async (ctx,next) => {
    const start:any = new Date();					          // 响应开始时间
    let intervals								              // 响应间隔时间
    try {
        await next();
        intervals = new Date() as any - start;
        httpLogger.info(formatText.response(ctx, intervals))	  //记录响应日志
    } catch (error) {
        intervals = new Date() as any - start;
        httpLogger.error(formatText.error(ctx,error,intervals)) //记录异常日志
    }
})

// 使用通信由中间件
app.use(SocketRouter.routes())
app.use(SocketRouter.allowedMethods())

// 设备状态统计中间件
app.use(DeviceStatsRouter.routes())
app.use(DeviceStatsRouter.allowedMethods())


const socket = (port:number | string):Server => {
    
    app.on("error",(err) => {
        logger.error("Koa应用错误:", err);
    })
    return app.listen(port,() => {
        logger.info("http://127.0.0.1:"+ port +" is running")
    })
    .on('error',(err) => {
        logger.error('HTTP服务器启动错误:', err);
    })
    
}

export default socket